﻿/*
 Copyright aswing.org, see the LICENCE.txt.
*/
package com.riatimes.util
{

	import flash.utils.getQualifiedClassName;
	import flash.system.ApplicationDomain;
	import flash.display.DisplayObject;

	/**
	 *
	 * 反射类
	 *
	 */
	public class Reflection
	{
		/**
		 * 返回根据类名，和域创建实例
		 * @param fullClassName
		 * @param applicationDomain
		 * @return
		 *
		 */
		public static function createDisplayObjectInstance(fullClassName:String, applicationDomain:ApplicationDomain=null):*
		{
			return createInstance(fullClassName, applicationDomain);
		}

		/**
		 * 根据类名，和域创建实例
		 * @param fullClassName
		 * @param applicationDomain
		 * @return
		 *
		 */
		public static function createInstance(fullClassName:String, applicationDomain:ApplicationDomain=null):*
		{
			var assetClass:Class=getClass(fullClassName, applicationDomain);
			if (assetClass != null)
			{
				return new assetClass();
			}
			return null;
		}

		/**
		 *根据类名返回指定域里的类
		 * @param fullClassName
		 * @param applicationDomain
		 * @return
		 *
		 */
		public static function getClass(fullClassName:String, applicationDomain:ApplicationDomain=null):Class
		{
			if (applicationDomain == null)
			{
				applicationDomain=ApplicationDomain.currentDomain;
			}
			var assetClass:Class=applicationDomain.getDefinition(fullClassName) as Class;
			return assetClass;
		}

		/**
		 *返回对象的完全限定类名。
		 * @param o
		 * @return
		 *
		 */
		public static function getFullClassName(o:*):String
		{
			return getQualifiedClassName(o);
		}

		/**
		 *返回对象的类名
		 * @param o
		 * @return
		 *
		 */
		public static function getClassName(o:*):String
		{
			var name:String=getFullClassName(o);
			var lastI:int=name.lastIndexOf(".");
			if (lastI >= 0)
			{
				name=name.substr(lastI + 1);
			}
			return name;
		}

		/**
		 *返回对象的包名
		 * @param o
		 * @return
		 *
		 */
		public static function getPackageName(o:*):String
		{
			var name:String=getFullClassName(o);
			var lastI:int=name.lastIndexOf(".");
			if (lastI >= 0)
			{
				return name.substring(0, lastI);
			}
			else
			{
				return "";
			}
		}
	}

}